var module = angular.module('manager', [ 'ngRoute' ]);
module.service('SharedPropertiesService', function() {
	var username = "";
	var type = "";
	var conferenceName = "";
	var mine = "";
	return {
		getUsername : function() {
			return username;
		},
		setUsername : function(value) {
			username = value;
		},
		getConferenceName : function() {
			return conferenceName;
		},
		setConferenceName : function(value) {
			conferenceName = value;
		},
		getType : function() {
			return type;
		},
		setType : function(value) {
			type = value;
		},
		getMine : function() {
			return mine;
		},
		setMine : function(value) {
			mine = value;
		}
	};
});

module.controller("SessionController", function($http, $scope, $location,
		$rootScope, SharedPropertiesService) {
	if (SharedPropertiesService.getUsername() === "") {
		$location.path("/login");
	}
});

module.controller("LoginController",function($http, $scope, $location, $rootScope, SharedPropertiesService) {
	$scope.logout = function() {
		$http.get("rest/login/logout").success(function(data) {
			SharedPropertiesService.setUsername("");	
			SharedPropertiesService.setType("");
			$rootScope.loginUsername = "";
			$rootScope.loggedIn = "false";
			$rootScope.adminLoggedIn = "false";
			$rootScope.reg_success_div = "";
			var noString = "";
			$rootScope.loginUsername = noString;
			$location.path("/login");
		}).error(function(data) {
			alert(data);
		});
	};

	$scope.login = function() {
		$http.post('rest/login', $scope.newUser)
			.success(function(data) {
				if (data === "false") {
					$location.path("/login");
				} else {
				$http.get('rest/login/getType')
					.success(function(data) {
						if (data === "ADMIN") {
							$rootScope.adminLoggedIn = "true";
						} else {
							$rootScope.adminLoggedIn = "";
						}
						SharedPropertiesService.setType(data);
					})
					.error(function(data) {
						alert(data);
					});
					$rootScope.loggedIn = "true";
					$rootScope.loginUsername = $scope.newUser.user.username;
					$rootScope.reg_success_div = "";
					SharedPropertiesService.setUsername($scope.newUser.user.username);
				}
				$location.path("/home");
			})
			.error(function(data, status, headers, config) {
				alert(status);
			});
		};
	});

module.controller('ManagerController', function($http, $scope, $location,
		$rootScope, SharedPropertiesService) {

	$scope.isEmployee = function() {
		return SharedPropertiesService.getType() === "EMPLOYEE";
	};

	$scope.isLecturer = function() {
		return SharedPropertiesService.getType() === "LECTURER";
	};
	
	$scope.isMine = function () {
		console.log(SharedPropertiesService.getMine());
		return SharedPropertiesService.getMine() === "true";
	};

	$scope.changePassword = function() {
		var changePassword = $scope.profile.changePassword;
		var confirmPassword = $scope.profile.confirmPassword;
		if (changePassword === confirmPassword) {
			$http.post("rest/lecturer/changePassword", changePassword).success(
				function(data) {
					if (data === 'true') {
						alert("success");
					} else {
						alert("failure");
					}
				});
		} else {
			alert("passwords are differrent");
		}
	};
	$scope.changeEmail = function() {
		if (true) {// some validatons on email!!!
			$http.post("rest/lecturer/changeEmail", $scope.profile.changeEmail)
				.success(function(data) {
					if (data === 'true') {
						alert("success");
					} else {
						alert("failure");
					}
			});
		}
	};
	$scope.deactivateProfile = function() {
		var isActive = "false";
		$http.post("rest/lecturer/updatePrivilege", isActive).success(
			function(data) {
				alert('success');
			}).error(function(data) {
		alert("failure");
		});

	};
	$scope.loadCompanies = function() {
		$http.get('rest/company').success(function(data) {
			$scope.companies = data.company;
		});
	};
	$scope.loadConferences = function() {
		$http.get('rest/conferences').success(function(data) {
			$scope.conferences = data.conference;
		}).error(function(data) {
			 alert(data);
		});
	};

	$scope.loadProfile = function() {
		$scope.username = $rootScope.loginUsername;
		$http.get("rest/login/getUsername").success(function(data) {
			$scope.profile.confirmPassword = "";
		}).error(function(data) {
			alert("error");
			$scope.username = "Error!";
		});
	};
	
	$scope.isDisabled = function(){
		return $scope.disabled;
	};

	$scope.createLecture = function() {
		SharedPropertiesService.setConferenceName($scope.conferenceName);
		$location.path('/createLecture');
	};

	$scope.filterLecturesForLecturers = function() {
		if ($scope.category === "All") {
			$http.get('rest/conferences').success(function(data) {
				$scope.conferences = data.conference;
			}).error(function(data) {
				 alert(data);
			});
		} else if ($scope.category == "Favorite") {
			$http.get('rest/lecturer/getFavoriteConferences').success(
				function(data) {
					$scope.conferences = data.conference;
				}).error(function(data) {
				 alert(data);
			});
		}
	};
	
	$scope.filterLecturesForEmployees = function() {
		if ($scope.category === "All") {
			$http.get('rest/conferences').success(function(data) {
				$scope.conferences = data.conference;
			}).error(function(data) {
				// alert(data);
			});
		} else if ($scope.category == "Mine") {
			$http.get('rest/employee/getEmployeeConferences').success(
					function(data) {
						$scope.conferences = data.conference;
					}).error(function(data) {
				// alert(data);
			});
		}
		// alert($scope.stat);
	};

	$scope.redirect = function(redirectTo) {
		if (redirectTo === "home") {
			$location.path('/home');
		} else if (redirectTo === "conferences") {
			$location.path('/conferences');
		} else if (redirectTo === "messages") {
			$location.path('/messages');
		} else if (redirectTo === "messagesEmployee") {
			$location.path('/messagesEmployee');
		} else if (redirectTo === "register") {
			$location.path('/registration');
		} else if (redirectTo === "login") {
			$location.path('/login');
		} else if (redirectTo === "profile") {
			$location.path('/profile');
		} else if (redirectTo === "createCompany") {
			$location.path('/createCompany');
		} else if (redirectTo === "createEmployee") {
			$location.path('/createEmployee');
		} else if (redirectTo === "createConference") {
			$location.path('/createConference');
		} else if (redirectTo === "createLecture") {
			$location.path('/createLecture');
		} else if (redirectTo === "allEmployees") {
			$location.path('/allEmployees');
		} else if (redirectTo === "allCompanies") {
			$location.path('/allCompanies');
		} 
	};
});

module.controller('RegistrationController', function($http, $scope, $location, $rootScope, SharedPropertiesService) {
	$scope.createLecturer = function() {
		$http.post('rest/lecturer', $scope.newLecturer, {})
			.success(function(data) {
				res = data;
				if (res === "Registration successful!"){
					$rootScope.reg_success_div = res;
					$location.path("/login");
				}
				else {
					$scope.reg_fail_div = res;
				}
			});
	};
}).directive('validPasswordC',function() {
		return {
			require : 'ngModel',
			link : function(scope, elm, attrs, ctrl) {
				ctrl.$parsers.unshift(function(viewValue, $scope) {
					var noMatch = viewValue != scope.registration.password.$viewValue;
					ctrl.$setValidity('noMatch', !noMatch);
				});
			}
		};
});

module.controller('CompanyController', function($http, $scope, $location,
		SharedPropertiesService) {
	$scope.createCompany = function() {
		$http.post('rest/company', $scope.newCompany).success(function(data) {
			if (data !== '') {
				$location.path("/home");
			} else {
				alert('Exists company with this name');
			}
		});
	};
});

module.controller('ConferenceController',function($http, $scope, $location, $routeParams,SharedPropertiesService) {
	$scope.conferenceName = $routeParams.conferenceName;
	$scope.stat = 2;
	$scope.favorite = "";
	
	$scope.isEmployee = function() {
		return SharedPropertiesService.getType() === "EMPLOYEE";
	};

	$scope.isLecturer = function() {
		return SharedPropertiesService.getType() === "LECTURER";
	};
	
	$scope.isFavorite = function() {
		if (SharedPropertiesService.getType() === "LECTURER") {
			$http.get('rest/lecturer/' + $scope.conferenceName)
				.success(function(data) {
					if (data === "true") {
						$scope.favorite = "false";
					} else {
						$scope.favorite = "true";
					}
				}).error(function(data) {
					alert("Error in checking if conference is favorite");
				});
		}else{
			$scope.favorite = "false";
		}
		
		$http.get("rest/conferences/checkConferenceStartTime/"+$scope.conferenceName).success(function(data) {
		if(data === 'true'){
			$scope.disabled = false;
		}else{
			$scope.disabled = true;
		}
		
		}).error(function(data) {
			alert("error disabling Add conference button");
		});
	};

	$http.post('rest/conferences/getConferenceByName', $routeParams.conferenceName)
		.success(function(data) {
			$scope.conferenceLocation = data.conference.location;
			$scope.conferenceStartTime = data.conference.startTime;
			$scope.conferenceEndTime = data.conference.endTime;
			if (Object.prototype.toString.call(data.conference.lectures) === '[object Array]') {
				$scope.lectures = data.conference.lectures;
			} else	$scope.lectures = [ data.conference.lectures ];
		}).error(function(data) {
		});
	$scope.createConference = function() {
		var today = new Date();
		today.setHours(0,0,0, 0);
		today.setDate(today.getDate()+30);
		var startTime = new Date($scope.newConference.conference.startTime);
		startTime.setHours(0, 0, 0, 0);
		var endTime = new Date($scope.newConference.conference.endTime);
		endTime.setHours(0,0,0,0);
		
		if(today > startTime){
			$scope.conference_info="The conference must start after at least 30 days.";
		}else if(endTime<startTime){
			$scope.conference_info="End date cannot be before start date.";
		}else{
			$http.post('rest/conferences', $scope.newConference)
			.success(function(data) {
				if (data === '') {
					$scope.conference_info="Conference name must be unique!";
				} else {
					$location.path('/conferences');
				}
			}).error(function(data) {
				alert(data);
		});
		}
		};
		$scope.changeStatus = function() {
			if ($scope.status === "All") {
				$scope.stat = 2;
			} else if ($scope.status == "Approved") {
				$scope.stat = 1;
			} else if ($scope.status == "Not approved") {
				$scope.stat = -1;
			} else if ($scope.status == "Not seen") {
				$scope.stat = 0;
			}
		};
					//	
		$scope.isStatus = function(lecture) {
			if(typeof lecture !== 'undefined'){
				if (SharedPropertiesService.getType() === 'LECTURER') {
					return (lecture.status === 1);
				} else {
					if ($scope.stat === 2) {
						return true;
					} else {
						return (lecture.status == $scope.stat);
					}
				}
			}else{
				return false;
			}
		};

	$scope.addToFavourites = function() {
		$http.post('rest/lecturer/addConference/'+ $scope.conferenceName).success(function(data) {
		$scope.favorite = "false";
		}).error(function(data) {
			alert("fail");
		});
	};

	$http.get('rest/conferences').success(function(data) {
		$scope.conferences = data.conference;
	});

});

module.controller('SingleLectureController', function($http, $scope, $location, $routeParams, SharedPropertiesService) {
	$scope.lectureTitle = $routeParams.lectureTitle;
	// $scope.stat = 2;
	$http.post('rest/lecture/getLectureByTitle', $routeParams.lectureTitle).success(function(data) {
		$http.post('rest/lecture/getConferenceByLectureByTitle',$routeParams.lectureTitle)
			.success(function(data) {
				$scope.conferenceName = data.conference.name;
				$http.post('rest/employee/isMineConference', $scope.conferenceName).success(function(data){
					console.log(data);
					if (data === "true") {
						SharedPropertiesService.setMine(data);
					}else{
						SharedPropertiesService.setMine("false");
					}
				});
			});
		console.log(JSON.stringify(data.lecture, null, 4));
		$scope.lectureDescription = data.lecture.description;
		$scope.lecureLecturer = data.lecture.lecturer.name;
		$scope.lecureDate = data.lecture.date;
		$scope.lecureTime = data.lecture.time;
		$scope.lecureLength = data.lecture.length;

		if (data.lecture.status == 0) {
			$scope.lecureStatus = "Not seen";
		} else if (data.lecture.status == 1) {
			$scope.lecureStatus = "Approved";
		} else if (data.lecture.status == -1) {
			$scope.lecureStatus = "Not approved";
		}
	}).error(function(data) {
		alert("error");
	});

	$scope.approveLecture = function() {
		$http.post('rest/lecture/approveLectureByTitle', $routeParams.lectureTitle)
			.success(function(data) {
				
			}).error(function(data) {
							 alert(data);
			});
		$scope.lecureStatus = "Approved";
	};

	$scope.disapproveLecture = function() {
		$http.post('rest/lecture/disapproveLectureByTitle',$routeParams.lectureTitle).success(function(data) {
			}).error(function(data) {
		});
		$scope.lecureStatus = "Disapproved";
	};
});

module.controller('LectureController', function($http, $scope, $location, $rootScope, SharedPropertiesService) {
	$scope.createLecture = function() {
		var trans = {
			"transferConference" : {
				title : $scope.newLecture.lecture.title,
				description : $scope.newLecture.lecture.description,
				date : $scope.newLecture.lecture.date,
				time : $scope.newLecture.lecture.time,
				length : $scope.newLecture.lecture.length,
				confName : SharedPropertiesService.getConferenceName()
			}
		};

		$http.post('rest/conferences/getConferenceByName', SharedPropertiesService.getConferenceName())
			.success(function(data) {
				var startTime = new Date(data.conference.startTime);
				startTime.setHours(0, 0, 0, 0);
				var endTime = new Date(data.conference.endTime);
				endTime.setHours(0, 0, 0, 0);
				var lectureDate = new Date($scope.newLecture.lecture.date);
				lectureDate.setHours(0, 0, 0, 0);
				if ((startTime <= lectureDate && lectureDate <= endTime )|| 
					(startTime.valueOf() === lectureDate.valueOf() || 
						endTime.valueOf() === lectureDate.valueOf())) {
					$http.post('rest/lecture', trans)
						.success(function(data) {
							if (data === '') {
								$scope.lecture_info = "Lecture title must be unique.";
							} else {
								$location.path('/conference/'+ $scope.newLecture.lecture.title);
							}
						}).error(function(data) {
							alert(data);
						});
				} else {
					$scope.lecture_info = "The date must be between " + data.conference.startTime.slice(0,10) +
					" and " + data.conference.endTime.slice(0,10) +".";
				}
			});
	};
});
module.controller('EmployeeController', function($http, $scope, $location) {
	$scope.createEmployee = function() {
		var employee = {
			"transferEmployee" : {
				username : $scope.newEmployee.employee.username,
				password : $scope.newEmployee.employee.password,
				email : $scope.newEmployee.employee.email,
				name : $scope.newEmployee.employee.name,
				companyName : $scope.newEmployee.employee.company.companyName
			}
		};
		$http.post('rest/employee', employee).success(function(data) {
			if (data !== '') {
				$location.path("/home");
			} else {
				alert('Existing username');
			}

		}).error(function(data) {
			 alert(data);
		});
	};
	$http.get('rest/company').success(function(data) {
		$scope.companies = data.company;
	});

	$http.get('rest/employee').success(function(data) {
		$scope.employees = data.employee;
	});

}).directive('validEmployee', function() {
	return {
		require : 'ngModel',
		link : function(scope, elm, attrs, ctrl) {
			ctrl.$parsers.unshift(function(viewValue, $scope) {
				var noMatch = false;
				ctrl.$setValidity('noMatch', !noMatch);
			});
		}
	};
});

module.controller('MessagesController', function($scope, $http, $routeParams) {

	$scope.loadMessages = function() {
		$http.get('rest/lmessages/approvedOrNot').success(function(data) {
			$scope.approvedLec = data.lecture;
		});
		$http.get('rest/lmessages/newConferencesForMe').success(function(data) {
			$scope.newConf = data.conference;
		});
		$http.get('rest/lmessages/notAddedToConf').success(function(data) {
			$scope.notAddedLec = data.conference;
		});
	};
});

module.controller('EmployeeMessagesController', function($scope, $http,
		$routeParams) {
	$scope.loadEMessages = function() {
		$http.get('rest/emessages/newLectures').success(function(data) {
			$scope.newLectures = data.lecture;
		});
		$http.get('rest/emessages/notSeen').success(function(data) {
			$scope.notSeen = data.lecture;
		});
	};
});

module.config([ '$routeProvider', function($routeProvider) {
	$routeProvider.when('/login', {
		templateUrl : "Views/Login.html",
		controller : "LoginController"
	}).when('/messages', {
		templateUrl : "Views/Messages.html",
		controller : "MessagesController"
	}).when('/messagesEmployee', {
		templateUrl : "Views/EmployeeMessages.html",
		controller : "EmployeeMessagesController"
	}).when('/conferences', {
		templateUrl : "Views/Conferences.html",
		controller : "ManagerController"
	}).when('/conferences/:conferenceName', {
		templateUrl : "Views/Conference.html",
		controller : "ConferenceController"
	}).when('/conference/:lectureTitle', {
		templateUrl : "Views/Lecture.html",
		controller : "SingleLectureController"
	}).when('/home', {
		templateUrl : "Views/Home.html",
		controller : "ManagerController"
	}).when('/registration', {
		templateUrl : "Views/Registration.html",
		controller : "RegistrationController"
	}).when('/allCompanies', {
		templateUrl : "Views/AllCompanies.html",
		controller : "ManagerController"
	}).when('/createCompany', {
		templateUrl : "Views/NewCompany.html",
		controller : "CompanyController"
	}).when('/createConference', {
		templateUrl : "Views/AddConference.html",
		controller : "ConferenceController"
	}).when('/createLecture', {
		templateUrl : "Views/NewLecture.html",
		controller : "LectureController"
	}).when('/profile', {
		templateUrl : "Views/Profile.html",
		controller : "ManagerController"
	}).when('/createEmployee', {
		templateUrl : "Views/NewEmployee.html",
		controller : "EmployeeController"
	}).when('/allEmployees', {
		templateUrl : "Views/AllEmployees.html",
		controller : "EmployeeController"
	}).otherwise({
		redirectTo : "/login"
	});
} ]);
